package com.starhub.base.license.utils;

import java.nio.charset.StandardCharsets;  
import java.security.KeyFactory;  
import java.security.PublicKey;  
import java.security.Signature;  
import java.util.Base64;  

/**
 * 校验License文件
 */
public class LicenseValidator {  
    public static boolean validateLicense(String licensePath, String publicKeyPath) throws Exception {  
        // 加载License文件内容  
        String licenseContent = new String(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(licensePath)), StandardCharsets.UTF_8);  

        // 解析License数据和签名  
        String[] parts = licenseContent.split("\nSignature=");  
        String licenseData = parts[0];  
        String signatureBase64 = parts[1];  

        // 加载公钥  
        PublicKey publicKey = KeyUtil.loadPublicKey(publicKeyPath);  

        // 验证签名  
        Signature signature = Signature.getInstance("SHA256withRSA");  
        signature.initVerify(publicKey);  
        signature.update(licenseData.getBytes(StandardCharsets.UTF_8));  

        byte[] signatureBytes = Base64.getDecoder().decode(signatureBase64);  
        boolean isValid = signature.verify(signatureBytes);  

        if (!isValid) {  
            System.out.println("License签名验证失败");  
            return false;  
        }  

        // 校验License数据  
        for (String line : licenseData.split("\n")) {  
            String[] keyValue = line.split("=");  
            switch (keyValue[0]) {  
                case "AuthCode":  
                    String macHash = MacAddressUtil.getMacAddressHash();  
                    if (!keyValue[1].equals(macHash)) {  
                        System.out.println("MAC地址不匹配");  
                        return false;  
                    }  
                    break;  
                case "ExpiryDate":  
                    if (System.currentTimeMillis() > new java.text.SimpleDateFormat("yyyy-MM-dd").parse(keyValue[1]).getTime()) {  
                        System.out.println("License已过期");  
                        return false;  
                    }  
                    break;  
                default:  
                    // 其他字段可根据需要校验  
                    break;  
            }  
        }  
        return true;  
    }  

    private static PublicKey loadPublicKey(String publicKeyPath) throws Exception {  
        byte[] keyBytes = java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(publicKeyPath));  
        java.security.spec.X509EncodedKeySpec spec = new java.security.spec.X509EncodedKeySpec(keyBytes);  
        KeyFactory kf = KeyFactory.getInstance("RSA");  
        return kf.generatePublic(spec);  
    }  
}